<?php

require_once 'lib/bi/prototypes/view.base.php';
require_once 'lib/bi/core/html_helpers.php';

class CEntityFormView extends BaseView{
	protected $tplfn=NULL;
	protected $target='';
	protected $e=NULL;
	
	function __construct($p,$tplfn){
		$this->tplfn=$tplfn;
		parent::__construct($p);
	}
	
	function __destruct(){
	
	}
	
	function generateTPL(){
		$tpl ="<form method='POST' action='".$this->target."' >\n";
		$tpl.='<input type="hidden" name="__sender" value="<?=$_SERVER["REQUEST_URI"];?>" />'."\n";
		$tpl.="	<table>\n";
		$tpl.="		<thead>\n";
		$tpl.="			<tr class='error'><td colspan='2'><?php	if(isset(\$_GET['error']))echo \$_GET['error']; ?></td></tr>\n";
		$tpl.="		</thead>\n";
		$tpl.="		<tbody>\n";
		foreach(array_keys($this->e->fields) as $fldn){
			if($fldn=='id')$rowclass='hidden';
			else
			if(substr($fldn,-3)=='_id')$rowclass='hidden';
			else $rowclass='';
			$tpl.="			<tr class='$rowclass'>\n";
			$tpl.="				<td class='form_field_name_cell'><?=translate('$fldn');?></td>\n";
			$tpl.="				<td class='form_field_input_cell'><?=\$this->e->".$fldn."->input();?></td>\n";
			$tpl.="			</tr>\n";
		};
		$tpl.="			<tr>\n";
		$tpl.="				<td></td>\n";
		$tpl.="				<td><input type='submit' value='<?=translate(\"submit\");?>' /></td>\n";
		$tpl.="			</tr>\n";
		$tpl.="		</tbody>\n";
		$tpl.="	</table>\n";		
		$tpl.="</form>\n";
		console_log('View regenerated:'.$this->tplfn);
		file_put_contents($this->tplfn, $tpl);
	}
	
	function render(&$p){
		if(!isset($p['entity']))throw new Exception('FormViews entity parameter not set');
		$this->e=&$p['entity'];
		if(isset($p['target']))$this->target=$p['target'];else $this->target='do'.$_SERVER['REQUEST_DATA'][ACTION].'.html';
		if(!file_exists($this->tplfn))$this->generateTPL();
		include $this->tplfn;	
	}




}
